#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "tda_sheet.h"
#include "tda_synth.h"
#include "common.h"
#include "ondamod.h"



float gen_mod_wave_sample (adt_synth_t * instrument, adt_sheet_t * notes, float time, size_t n_note){
	float amp, mod_coef;
	amp=gen_wave_sample(instrument, notes, time, n_note);
	mod_coef=modulation_multiplier(instrument, notes, time, n_note);
	return amp*mod_coef;
}

float modulation_multiplier(adt_synth_t * modulation, adt_sheet_t * timing, float t, size_t n_note){
	float at, d, dt, arg0, arg1, arg2, sust_aux;
	float (* fa) (float, float, float, float);
	float (* fs) (float, float, float, float);
	float (* fd) (float, float, float, float);
	d=adt_sheet_get_length(timing, n_note);
	at=adt_synth_get_function_arg(modulation, ATTACK, 0);
	arg0=adt_synth_get_function_arg(modulation, SUSTAIN, 0);
	dt=adt_synth_get_function_arg(modulation, DECAY, 0);
	fa=adt_synth_get_function(modulation, ATTACK);
	fs=adt_synth_get_function(modulation, SUSTAIN);
	fd=adt_synth_get_function(modulation, DECAY);
	
	if (t>=0 && t<at){
	arg1=adt_synth_get_function_arg(modulation, ATTACK, 1);
	arg2=adt_synth_get_function_arg(modulation, ATTACK, 2);
	return (*fa)(t, at, arg1, arg2);
	}
	if (t>=at && t<d){
	arg1=adt_synth_get_function_arg(modulation, SUSTAIN, 1);
	arg2=adt_synth_get_function_arg(modulation, SUSTAIN, 2);
	return (*fs)(t-at, arg0, arg1, arg2);
	}
	if (t>=d && t<d+dt){
	arg1=adt_synth_get_function_arg(modulation, SUSTAIN, 1);
	arg2=adt_synth_get_function_arg(modulation, SUSTAIN, 2);
	sust_aux=(*fs)(d-at, arg0, arg1, arg2);
	arg1=adt_synth_get_function_arg(modulation, DECAY, 1);
	arg2=adt_synth_get_function_arg(modulation, DECAY, 2);
	return sust_aux*(*fd)(t-d, dt, arg1, arg2);
	}
	return 0;

}

float gen_wave_sample (adt_synth_t * instrument, adt_sheet_t * note, float t, size_t n_note){ /* a t se le pasa t + d */
	size_t i;
	float y, harm_int, harm_mult, it, f;
	y=0;
	it = adt_sheet_get_start_t(note, n_note);
	f=adt_sheet_get_frequency(note, n_note);

	for (i=0; i<adt_synth_get_harmonics_qty(instrument); i++){
		harm_int = adt_synth_get_harmonic_intensity(instrument,i);
		harm_mult = adt_synth_get_harmonic_multiplier(instrument,i);
		y+=harm_int*sin(2*PI*f*harm_mult*(t-it));
	}
	
	return y;
}
